package com.hxzy.controller;

import com.hxzy.pojo.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wzm
 * @create 2024-03-07 16:06
 * project_name:JavaWeb2401
 * @Description
 */
@Slf4j
@RestController
public class CookieController {
    //模拟登录成功后通知浏览器存储Cookie
    @GetMapping("/setCookie")
    public Result cookie1(HttpServletResponse response){
        //该方法模拟了登录成功 服务通知浏览器保存cookie
        //创建Cookie对象  存储cookie中的值 key-value
        Cookie cookie = new Cookie("login_name","zs");
        //通知给浏览器保存
        response.addCookie(cookie);
        return Result.success();

    }


    //测试是否能够获得上一次请求存储在浏览器中的cookie
    @GetMapping("/getCookie")
    public Result cookie2(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        //对获得的所有cookie进行遍历
        for (Cookie cookie:cookies){
           if(cookie.getName().equals("login_name")){
               //获取cookie的值
               System.out.println(cookie.getValue());
           }
        }

        return Result.success();

    }




    //存储session
    @GetMapping("/setSession")
    public Result session(HttpServletRequest request,HttpSession session){
        //在服务器存储session相关的知识
//        HttpSession session = request.getSession();
        //session又叫域对象 request就是
        session.setAttribute("loginUser","tom");
        return Result.success();
    }

    //获取session
    @GetMapping("/getSession")
    public Result session1(HttpSession session){
        //从服务器获取session
        String name = (String) session.getAttribute("loginUser");
        System.out.println(name);
        return Result.success(name);
    }


}
